package com.example.basic.web;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.Tracer;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

/**
 * 降级
 * 2024/12/11 14:51
 *
 * @author chenjh
 */
@RestController
public class DegradeController {

    /**
     * 降级规则
     */
    @PostConstruct
    public void initRule() {
        List<DegradeRule> rules = new ArrayList<>();
        DegradeRule rule = new DegradeRule();
        rule.setResource("demo2");
        rule.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_COUNT);
        rule.setTimeWindow(60);
        rule.setCount(1);
        rule.setStatIntervalMs(30000);
        rule.setMinRequestAmount(1);
        rules.add(rule);
        DegradeRuleManager.loadRules(rules);
    }

    //正常请求 http://127.0.0.1:8080/demo2?name=lisi
    //异常请求 http://127.0.0.1:8080/demo2?name=error
    @RequestMapping("/demo2")
    @ResponseBody
    public String demo2(@RequestParam(name = "name", defaultValue = "unknown user") String name) {
        Entry entry = null;
        try {
            entry = SphU.entry("demo2");
            if ("error".equals(name)) {
                throw new RuntimeException("error");
            }
            return "Hello " + name;
        } catch (BlockException ex) {
            // 处理被降级的逻辑
            return "降级策略！";
        } catch (Throwable t) {
            // 必须要手动记录异常，否则不算
            Tracer.traceEntry(t, entry);
            return "error";
        } finally {
            if (entry != null) {
                entry.exit();
            }
        }
    }


    //正常请求 http://127.0.0.1:8080/demo2Annotation?name=lisi
    //异常请求 http://127.0.0.1:8080/demo2Annotation?name=error
    @RequestMapping("/demo2Annotation")
    @ResponseBody
    @SentinelResource(value = "demo2", blockHandler = "demo2AnnotationBlock")
    public String demo2Annotation(@RequestParam(name = "name", defaultValue = "unknown user") String name) {
        if ("error".equals(name)) {
            throw new RuntimeException("error");
        }
        return "Hello " + name;
    }

    public String demo2AnnotationBlock(String name, BlockException e) {
        return "熔断降级！";
    }
}
